/**
 * raycaster 拾取场景物体案例
 */

import { Tshare } from "../utils/Tshare";
import * as THREE from 'three'

let container = document.querySelector("#app"),
T = new Tshare({container}),sphere = null,spotLight = null,
pointer = new THREE.Vector2(),raycaster = new THREE.Raycaster();

init();
animate();

function init() {
    T.initEnv(container);
    T.initOrbitControls();
    sphere = T.createSphereMesh();
    let uniforms = {
        rimColor: { value: new THREE.Color(0x04A1FF) },
        rimPower: { value: 1 },
    }
    sphere.material.onBeforeCompile = function (shader) {
        shader.uniforms.rimColor = uniforms.rimColor;
        shader.uniforms.rimPower = uniforms.rimPower;

        shader.fragmentShader = /* glsl */`
                    uniform vec3 rimColor;
                    uniform float rimPower;
                        ${shader.fragmentShader.replace(
            '#include <dithering_fragment>',
            '#include <dithering_fragment>\n\tfloat dotNV = 1.0-saturate( dot( normal, geometry.viewDir ) );\n\tgl_FragColor.rgb += rimPower*dotNV*rimColor;'
        )}
                `;
    };
    T.sceneGraph.add(sphere);
    // T.scene.add(new THREE.AxesHelper(2))
    addLight();
    container.addEventListener('click',selectSceneGraph)
}
function animate() {
    requestAnimationFrame(animate);
    T.renderer.render(T.scene,T.camera);
}

function addLight() {
    spotLight = new THREE.SpotLight(0xffffff,0.3);
    spotLight.position.set(0,80,80);
    spotLight.angle = Math.PI/8;
    T.sceneGraph.add(spotLight)
}
function selectSceneGraph(e){
    pointer.set(
        ((e.clientX - container.getBoundingClientRect().left)/container.offsetWidth) * 2 -1,
        -((e.clientY - container.getBoundingClientRect().top)/container.offsetHeight) * 2 + 1
    );
    raycaster.setFromCamera(pointer,T.camera);
    let intersects = raycaster.intersectObjects(T.sceneGraph.children,false);
    if(intersects.length == 0) return;
    let intersect = intersects[0].object;
    intersect.material.needsUpdate = true
    intersect.material.color = new THREE.Color(0xffffff * Math.random());
    intersect.material.transparent = true;
    intersect.material.opacity = Math.random()
}